package db

import (
	"context"
	"errors"
	"fmt"
	"github.com/glebarez/sqlite"
	"gorm.io/gorm"
	"sync"
)

type Mp4Item struct {
	Name   string `gorm:"primary_key"`
	Upload bool   `gorm:"upload"`
}

var db *gorm.DB = nil
var lock sync.Mutex

func Opendb(name string) (*gorm.DB, error) {
	var err error
	db, err = gorm.Open(sqlite.Open(name), &gorm.Config{})
	if err != nil {
		return nil, err
	}
	_ = db.Exec("PRAGMA synchronous = off;")
	err = db.AutoMigrate(&Mp4Item{})
	return db, err
}

func SaveMp4ToDb(ctx context.Context, file string) error {
	if db == nil {
		return errors.New("db not init")
	}

	fmt.Println("save file to db", file)

	lock.Lock()
	defer lock.Unlock()
	item := Mp4Item{
		Name:   file,
		Upload: false,
	}

	tx := db.WithContext(ctx).Create(&item)
	if tx.Error != nil {
		fmt.Println(tx.Error)
	}
	return tx.Error
}
func GetRemainCount(ctx context.Context) (int64, int64) {
	if db == nil {
		return 0, 0
	}
	lock.Lock()
	defer lock.Unlock()
	var count int64 = 0
	var all int64 = 0
	db.WithContext(ctx).Model(&Mp4Item{}).Where("upload=false").Count(&count)
	db.WithContext(ctx).Model(&Mp4Item{}).Count(&all)
	return all, count
}
func GetUnUpload(ctx context.Context) string {
	if db == nil {
		return ""
	}
	lock.Lock()
	defer lock.Unlock()
	item := Mp4Item{
		Upload: false,
	}
	var count int64 = 0
	db.WithContext(ctx).Model(&Mp4Item{}).Where("upload=false").Count(&count)
	if count <= 0 {
		return ""
	}

	tx := db.WithContext(ctx).Model(&Mp4Item{}).Where("upload=false").First(&item)
	if tx.Error != nil {
		fmt.Println(tx.Error)
		return ""
	}
	return item.Name
}
func SetFileFlag(ctx context.Context, name string) {
	if db == nil {
		return
	}
	fmt.Println("set uploaded ", name)
	lock.Lock()
	defer lock.Unlock()

	tx := db.WithContext(ctx).Model(&Mp4Item{}).
		Where("name = ?", name).UpdateColumn("upload", true)
	if tx.Error != nil {
		fmt.Println(tx.Error)
	}
}
